package me.shihao.serialportdemo.serialport

import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.util.Log
import com.felhr.usbserial.UsbSerialDevice
import com.felhr.usbserial.UsbSerialInterface
import com.hoho.android.usbserial.driver.UsbSerialPort
import com.hoho.android.usbserial.driver.UsbSerialProber
import com.hoho.android.usbserial.util.SerialInputOutputManager
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * author: shihao
 * date: 2021/5/28 10:21
 * description:
 */
class SerialPortManager {
    private val TAG = javaClass.simpleName

    companion object {
        val instance: SerialPortManager by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            SerialPortManager()
        }
    }

    interface OnReceivedDataListener {
        fun onReceivedData(data: String)
    }

    private var usbSerialPort: UsbSerialDevice? = null
    private val listeners = arrayListOf<OnReceivedDataListener>()

    private var usbSerialDevice: UsbSerialDevice? = null

    fun addOnReceivedDataListener(listener: OnReceivedDataListener) {
        if (listeners.contains(listener)) {
            listeners.remove(listener)
        }
        listeners.add(listener)
    }

    fun removeOnReceivedDataListener(listener: OnReceivedDataListener) {
        if (listeners.contains(listener)) {
            listeners.remove(listener)
        }
    }

    fun connectDevice(context: Context, usbDevice: UsbDevice) {
        val manager = context.getSystemService(Context.USB_SERVICE) as UsbManager
        val availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager)
        if (availableDrivers.isEmpty()) {
            //未获取到usb设备
            Log.d(TAG, "未获取到usb设备")
            return
        }
        val driver = availableDrivers.find {
            it.device.deviceName == usbDevice.deviceName
        } ?: availableDrivers[0]
        val connection = manager.openDevice(driver.device)
        if (connection == null) {
            Log.d(TAG, "打开usb设备失败")
            return
        }
        try {
            usbSerialPort = UsbSerialDevice.createUsbSerialDevice(driver.device, connection)
            usbSerialPort?.open()
            usbSerialPort?.setBaudRate(9600)
            usbSerialPort?.setDataBits(UsbSerialInterface.DATA_BITS_8)
            usbSerialPort?.setStopBits(UsbSerialInterface.STOP_BITS_1)
            usbSerialPort?.setParity(UsbSerialInterface.PARITY_NONE)
            usbSerialPort?.read { data ->
                val text = String(data)
                listeners.forEach {
                    it.onReceivedData(text)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d(TAG, "连接usb设备失败")
            disconnectDevice()
        }
    }

    fun disconnectDevice() {
        Log.d(TAG, "断开usb设备")
        try {
            usbSerialPort?.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        usbSerialPort = null
    }

}